<script lang="ts">
  import { createEventDispatcher, onDestroy, onMount, tick } from 'svelte';
  import useDrag from '../hooks/useDrag';
  import { AvatarType } from '../types/broadcastMini';
  import livePng from '../asset/images/live.svg';
  import type { Position } from '../types/vtuber';
  import { debounce, setPosition } from '../utils/tools';
  const emit = createEventDispatcher();
  export let dragAble: boolean = true;
  export let isShow: boolean = true;
  export let position: Position;

  const tipsOptions = {
    firstEnter: '您好，我是您的专属AI助手',
    isAutoplay: '最新解盘为您自动报送',
    otherdayFirstEnter: ''
  };
  let showTips: boolean = true;
  export let isAutoplay: boolean = false;
  export let isPlaying: boolean = false;
  export let isFirstEnter: boolean = false;
  // 是否是49内核
  export let isChrome49: boolean = false;
  let isClickRightClick: boolean = false;

  let tips = '';
  $: {
    tips = isFirstEnter
      ? tipsOptions.firstEnter
      : isAutoplay
        ? tipsOptions.isAutoplay
        : tipsOptions.otherdayFirstEnter;
  }
  // 右键操作
  const contextmenu = (event) => {
    // 阻止默认右键菜单
    event.preventDefault();
    if (isChrome49) {
      return;
    }
    isClickRightClick = true;
  };
  // 取消右键状态
  const flipContextmenu = () => {
    isClickRightClick = false;
  };

  // 关闭播放
  const turnoffPlay = (event) => {
    event.stopPropagation();
    // 关闭播放
    emit('turnoffPlay');
    isClickRightClick = false;
  };
  // 切换最小化状态
  const toggleMiniStatus = () => {
    if (isChrome49) {
      return;
    }
    showTips = false;
    emit('toggleMiniStatus', { isMiniStatus: false });
  };
  let mousedownTime: Date;
  // 鼠标按下
  const mousedownFn = () => {
    mousedownTime = new Date();
  };
  // 鼠标谈起
  const mouseupFn = (event: MouseEvent) => {
    if (event.button !== 0) {
      return;
    }
    const timediff = new Date().getTime() - mousedownTime.getTime();
    if (timediff < 200) {
      toggleMiniStatus();
    }
  };
  // 切换自动播放
  const toggleAutoplay = (event) => {
    event.stopPropagation();
    emit('toggleAutoplay');
    isClickRightClick = false;
  };

  let broadcastMini: HTMLElement | void;
  export let avatarType: AvatarType = AvatarType.Gold;
  // 计算距离右边屏幕宽度
  const getRight = debounce(() => {
    if (!tipsDom) {
      return;
    }
    const { right } = tipsDom.getBoundingClientRect();
    const distanceToRight = window.innerWidth - right;
    const distrance = tipsPositon === 'left' ? 250 : 10;
    tipsPositon = distanceToRight < distrance ? 'left' : 'right';
  }, 200);
  const { setDragAble, removeDragAble } = useDrag(getRight);

  let tipsDom: HTMLElement | void;
  let tipsPositon: 'left' | 'right' = 'right';

  onMount(() => {
    if (broadcastMini) {
      setPosition(position, broadcastMini);
      dragAble && setDragAble(broadcastMini);
    }
    document.addEventListener('click', flipContextmenu);
    // @ts-ignore
    window.addEventListener('resize', getRight);
    // dragAble===true说明投顾直播页面 dragAble===false说明金融大师首页
    if (dragAble) {
      tick().then(() => {
        getRight();
      });
    } else {
      // 金融大师首页有动画
      setTimeout(() => {
        getRight();
      }, 3500);
    }
  });
  onDestroy(() => {
    if (broadcastMini && dragAble) {
      removeDragAble(broadcastMini);
    }
    // @ts-ignore
    window.removeEventListener('resize', getRight);
    document.removeEventListener('click', flipContextmenu);
  });
</script>

<!-- svelte-ignore a11y-click-events-have-key-events -->
<div
  class="broadcast-mini {[AvatarType.Blud, AvatarType.Metal].includes(avatarType)
    ? 'avatar2'
    : 'avatar1'} {dragAble ? 'draggable' : 'no-draggable'}"
  bind:this={broadcastMini}
  style="display:{isShow ? 'block' : 'none'}"
  on:contextmenu={contextmenu}
  on:mousedown={mousedownFn}
  on:mouseup={mouseupFn}
>
  <div class="container">
    {#if !isPlaying}
      <span class="title">AI小助理</span>
    {/if}
    {#if showTips && tips}
      <div class="tips {tipsPositon}" bind:this={tipsDom}>
        {@html isChrome49 ? '系统版本过低，暂无法体验<br/>此功能，敬请期待后续优化' : tips}
      </div>
    {/if}
    {#if isClickRightClick}
      <div
        class="controls"
        on:mousedown={(e) => {
          e.stopPropagation();
        }}
        on:mouseup={(e) => {
          e.stopPropagation();
        }}
      >
        {#if isAutoplay}
          <div on:click={toggleAutoplay}>关闭自动播报</div>
        {:else}
          <div on:click={toggleAutoplay}>开启自动播报</div>
        {/if}
        {#if isPlaying}
          <div on:click={turnoffPlay}>退出助手</div>
        {/if}
      </div>
    {/if}
    {#if isPlaying}
      <div class="circle">
        <div class="inner">
          <img src={livePng} alt="" class="live" /><span>播放中</span><img
            src="//i.thsi.cn/staticS3/mobileweb-upload-static-server.img/m/atom/090d0a19-f52a-4dbe-829f-cc9cf9928d2d.png"
            alt=""
            class="close"
            on:click={turnoffPlay}
            on:mousedown={(e) => {
              e.stopPropagation();
            }}
            on:mouseup={(e) => {
              e.stopPropagation();
            }}
          />
        </div>
      </div>
    {/if}
  </div>
</div>

<style lang="less">
  .broadcast-mini {
    width: 82px;
    height: 82px;
    position: absolute;
    background-size: contain;
    background-repeat: no-repeat;
    z-index: 999999;
    &.draggable {
      cursor: move;
    }
    &.no-draggable {
      cursor: inherit;
    }
    .container {
      width: 100%;
      height: 100%;
      position: relative;
    }
    .title {
      font-family: MicrosoftYaHeiSemibold;
      position: absolute;
      font-size: 13px;
      color: #e1a647;
      letter-spacing: 0;
      text-shadow: 0 0 3px rgba(0, 0, 0, 0.6);
      font-weight: 600;
      top: 65%;
      left: 48%;
      transform: translate(-50%, -50%);
      white-space: nowrap;
    }
    .tips {
      position: absolute;
      top: 8px;
      left: 58px;
      font-family: PingFangSC-Regular;
      font-size: 14px;
      color: #ffffff;
      letter-spacing: 0;
      text-align: justify;
      font-weight: 400;
      background: #c4861b;
      border-radius: 6px 6px 6px 0;
      white-space: nowrap;
      padding: 2px 6px 2px 6px;
      &.left {
        left: initial;
        right: 68px;
        border-radius: 6px 6px 0 6px;
        &::after {
          left: initial;
          right: 0;
          border-top: 2px solid #c4861b;
          border-left: 3px solid transparent;
          border-right: 3px solid #c4861b;
          border-bottom: 3px solid transparent;
        }
      }
      &::after {
        content: '';
        position: absolute;
        border-top: 2px solid #c4861b;
        border-left: 3px solid #c4861b;
        border-right: 3px solid transparent;
        border-bottom: 3px solid transparent;
        left: 0;
        bottom: -5px;
      }
    }
    .circle {
      position: absolute;
      width: 32px;
      height: 32px;
      left: 40px;
      bottom: -3px;
      border: 1px solid rgba(219, 160, 59, 0.3);
      border-radius: 50%;
      &:hover {
        border: 1px solid transparent;
        .inner {
          width: 88px;
        }
      }
      .inner {
        position: absolute;
        width: 24px;
        height: 24px;
        display: flex;
        align-items: center;
        align-items: center;
        background: #c4861b;
        border-radius: 12px;
        top: 4px;
        left: 4px;
        transition: width 0.3s ease-in-out;
        overflow: hidden;
        box-sizing: border-box;
        .live {
          width: 12px;
          height: 12px;
          margin-left: 6px;
          margin-top: -2px;
        }
        span {
          font-family: PingFangSC-Regular;
          font-size: 14px;
          color: #ffffff;
          letter-spacing: 0;
          text-align: justify;
          font-weight: 400;
          white-space: nowrap;
          margin-left: 5.5px;
        }
        .close {
          width: 16px;
          height: 16px;
          margin-left: 2px;
          cursor: pointer;
        }
      }
    }
    .controls {
      position: absolute;
      left: 65px;
      top: 30px;
      background: #484848;
      border-radius: 2px;
      z-index: 2;
      cursor: pointer;
      div {
        width: 105px;
        height: 36px;
        display: flex;
        align-items: center;
        padding: 8px 10px;
        font-family: PingFangSC-Regular;
        font-size: 14px;
        color: #ffffff;
        letter-spacing: 0;
        text-align: justify;
        font-weight: 400;
        box-sizing: border-box;
      }
    }
  }
  .avatar1 {
    background-image: url('//i.thsi.cn/staticS3/mobileweb-upload-static-server.img/m/atom/703658d1-5060-4406-87a1-39dd65dd07ee.png');
  }
  .avatar2 {
    background-image: url('//i.thsi.cn/staticS3/mobileweb-upload-static-server.img/m/atom/61ee67e1-5a51-492b-8c6c-2fb82d83b671.png');
  }
</style>
